package com.sunchangming.stmdb;

import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

public class TMap<K, V> {
	private java.util.Map<K, V> data;
	private final String lockname;
	private final ReentrantLock lock = new ReentrantLock();

	TMap(String lockname) {
		this.lockname = lockname;
	}

	/**
	 * TODO: 这个如何实现事务级的一致性？
	 * 
	 * @param tx
	 * @return
	 */
	public int size(Transaction tx) {
		lock.lock();
		try {
			return data.size();
		} finally {
			lock.unlock();
		}
	}

	/**
	 * TODO: 这个如何实现事务级的一致性？
	 * 
	 * @param tx
	 * @return
	 */
	public boolean isEmpty(Transaction tx) {
		lock.lock();
		try {
			return data.isEmpty();
		} finally {
			lock.unlock();
		}
	}

	public boolean containsKey(Transaction tx, Object key) {
		throw new NotImpl();
	}

	public boolean containsValue(Transaction tx, Object value) {
		throw new NotImpl();
	}

	public V get(Transaction tx, Object key) {
		final Lockey lockey = LockManager.get(lockname, key);
		tx.add(lockey);
		V r;
		lock.lock();
		try {
			r = data.get(key);
		} finally {
			lock.unlock();
		}
		return r;
	}

	public V put(Transaction tx, K key, V value) {
		final Lockey lockey = LockManager.get(lockname, key);
		tx.add(lockey);
		V r;
		lock.lock();
		try {
			r = data.put(key, value);
		} finally {
			lock.unlock();
		}
		return r;
	}

	public V remove(Transaction tx, Object key) {
		final Lockey lockey = LockManager.get(lockname, key);
		tx.add(lockey);
		V r;
		lock.lock();
		try {
			r = data.remove(key);
		} finally {
			lock.unlock();
		}
		return r;
	}

	public void putAll(Transaction tx, Map<? extends K, ? extends V> m) {
		throw new NotImpl();
	}

	public void clear(Transaction tx) {
		lock.lock();
		try {
			//TODO: lock all , then clear
			throw new NotImpl();
		} finally {
			lock.unlock();
		}
	}
}
